<template>
  <view class="tasks-container">
    <!-- 统计卡片 -->
    <view class="stat-cards">
      <view class="stat-card">
        <view class="stat-icon orange">
          <uni-icons type="eye" size="24" color="#faad14"></uni-icons>
        </view>
        <view class="stat-info">
          <view class="stat-value">{{ statistics.pending }}</view>
          <view class="stat-label">待抽检</view>
        </view>
      </view>
      <view class="stat-card">
        <view class="stat-icon blue">
          <uni-icons type="calendar" size="24" color="#1890ff"></uni-icons>
        </view>
        <view class="stat-info">
          <view class="stat-value">{{ statistics.today }}</view>
          <view class="stat-label">今日抽检</view>
        </view>
      </view>
      <view class="stat-card">
        <view class="stat-icon green">
          <uni-icons type="checkbox-filled" size="24" color="#52c41a"></uni-icons>
        </view>
        <view class="stat-info">
          <view class="stat-value">{{ statistics.completed }}</view>
          <view class="stat-label">已完成</view>
        </view>
      </view>
    </view>

    <!-- 筛选标签 -->
    <view class="filter-section">
      <view class="filter-tabs">
        <view 
          v-for="tab in tabs" 
          :key="tab.value"
          :class="['tab-item', currentTab === tab.value ? 'active' : '']"
          @click="switchTab(tab.value)"
        >
          <text>{{ tab.label }}</text>
          <view v-if="tab.count > 0" class="tab-badge">{{ tab.count }}</view>
        </view>
      </view>
    </view>

    <!-- 任务列表 -->
    <scroll-view 
      scroll-y 
      class="list-container"
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <view v-if="list.length > 0">
        <view v-for="item in list" :key="item.applyId" class="task-item" @click="goToInspection(item)">
          <view class="item-header">
            <view class="item-title">
              <text class="merchant-name">{{ item.merchantName }}</text>
              <view v-if="item.auditStatus === '2'" class="urgent-badge">
                <uni-icons type="info-filled" size="14" color="#ff4d4f"></uni-icons>
                <text>需抽检</text>
              </view>
            </view>
            <view class="item-no">{{ item.applyNo }}</view>
          </view>
          
          <view class="item-content">
            <view class="content-row">
              <view class="content-item">
                <uni-icons type="calendar" size="16" color="#999"></uni-icons>
                <text class="label">入场时间：</text>
                <text class="value">{{ formatTime(item.entryTime) }}</text>
              </view>
            </view>
            <view class="content-row">
              <view class="content-item">
                <uni-icons type="location" size="16" color="#999"></uni-icons>
                <text class="label">入场地点：</text>
                <text class="value">{{ item.entryPlace }}</text>
              </view>
            </view>
            <view class="content-row">
              <view class="content-item">
                <uni-icons type="cart" size="16" color="#999"></uni-icons>
                <text class="label">商品数量：</text>
                <text class="value">{{ item.goodsCount || 0 }}种</text>
              </view>
              <view class="content-item">
                <uni-icons type="phone" size="16" color="#999"></uni-icons>
                <text class="label">车牌号：</text>
                <text class="value">{{ item.vehicleNo }}</text>
              </view>
            </view>
          </view>
          
          <view class="item-footer">
            <view class="goods-preview">
              <view class="goods-tag" v-for="(goods, idx) in getGoodsPreview(item)" :key="idx">
                {{ goods }}
              </view>
              <view v-if="item.goodsCount > 3" class="goods-more">+{{ item.goodsCount - 3 }}</view>
            </view>
            <view class="action-btn" @click.stop="goToInspection(item)">
              <uni-icons type="compose" size="16" color="#fff"></uni-icons>
              <text>开始抽检</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view v-else-if="!loading" class="empty-state">
        <uni-icons type="info" size="60" color="#ccc"></uni-icons>
        <text class="empty-text">{{ getEmptyText() }}</text>
      </view>

      <!-- 加载更多 -->
      <view v-if="loading && list.length > 0" class="loading-more">
        <uni-load-more status="loading"></uni-load-more>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { listAppointment } from '@/api/business/appointment.js'

export default {
  data() {
    return {
      currentTab: 'pending',
      tabs: [
        { label: '待抽检', value: 'pending', count: 0 },
        { label: '进行中', value: 'processing', count: 0 },
        { label: '已完成', value: 'completed', count: 0 }
      ],
      list: [],
      loading: false,
      refreshing: false,
      pageNum: 1,
      pageSize: 10,
      hasMore: true,
      statistics: {
        pending: 0,
        today: 0,
        completed: 0
      }
    }
  },
  onLoad() {
    this.loadStatistics()
    this.loadList(true)
  },
  methods: {
    // 加载统计数据
    async loadStatistics() {
      try {
        // 获取待抽检数量
        const pendingRes = await listAppointment({
          pageNum: 1,
          pageSize: 1,
          auditStatus: '2',
          checkStatus: '0'
        })
        this.statistics.pending = pendingRes.total || 0
        this.tabs[0].count = this.statistics.pending
        
        // 获取今日抽检数量
        const today = new Date().toISOString().split('T')[0]
        const todayRes = await listAppointment({
          pageNum: 1,
          pageSize: 1,
          auditStatus: '2',
          checkDate: today
        })
        this.statistics.today = todayRes.total || 0
        
        // 获取已完成数量
        const completedRes = await listAppointment({
          pageNum: 1,
          pageSize: 1,
          checkStatus: '1'
        })
        this.statistics.completed = completedRes.total || 0
        this.tabs[2].count = this.statistics.completed
        
      } catch (error) {
        console.error('加载统计失败:', error)
      }
    },
    
    // 加载列表
    async loadList(refresh = false) {
      if (this.loading) return
      if (!refresh && !this.hasMore) return
      
      this.loading = true
      if (refresh) {
        this.pageNum = 1
        this.hasMore = true
      }
      
      try {
        const params = {
          pageNum: this.pageNum,
          pageSize: this.pageSize
        }
        
        // 根据标签设置查询条件
        if (this.currentTab === 'pending') {
          params.auditStatus = '2'  // 需抽检
          params.checkStatus = '0'  // 未检查
        } else if (this.currentTab === 'processing') {
          params.auditStatus = '2'
          params.checkStatus = '2'  // 检查中
        } else if (this.currentTab === 'completed') {
          params.checkStatus = '1'  // 已检查
        }
        
        const res = await listAppointment(params)
        
        if (res.code === 200) {
          const data = res.rows || []
          const total = res.total || 0
          
          // 处理商品列表
          data.forEach(item => {
            if (item.appointmentDetailList) {
              item.goodsList = item.appointmentDetailList
              item.goodsCount = item.appointmentDetailList.length
            }
          })
          
          if (refresh) {
            this.list = data
          } else {
            this.list = [...this.list, ...data]
          }
          
          this.hasMore = this.list.length < total
          if (this.hasMore) {
            this.pageNum++
          }
        } else {
          if (refresh) {
            this.list = []
          }
          this.hasMore = false
        }
      } catch (error) {
        console.error('加载列表失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
        if (refresh) {
          this.list = []
        }
        this.hasMore = false
      } finally {
        this.loading = false
        this.refreshing = false
      }
    },
    
    // 切换标签
    switchTab(tab) {
      this.currentTab = tab
      this.loadList(true)
    },
    
    // 下拉刷新
    onRefresh() {
      this.refreshing = true
      this.loadStatistics()
      this.loadList(true)
    },
    
    // 加载更多
    loadMore() {
      this.loadList()
    },
    
    // 跳转到抽检页面
    goToInspection(item) {
      if (this.currentTab === 'completed') {
        // 已完成的查看详情
        uni.navigateTo({
          url: `/pages/check/detail?applyId=${item.applyId}`
        })
      } else {
        // 待抽检或进行中的进入抽检页面
        uni.navigateTo({
          url: `/pages/check/inspection?applyId=${item.applyId}&applyNo=${item.applyNo}`
        })
      }
    },
    
    // 获取商品预览
    getGoodsPreview(item) {
      if (!item.goodsList || item.goodsList.length === 0) return []
      return item.goodsList.slice(0, 3).map(g => g.goodsName)
    },
    
    // 获取空状态文本
    getEmptyText() {
      const map = {
        'pending': '暂无待抽检任务',
        'processing': '暂无进行中的任务',
        'completed': '暂无已完成的任务'
      }
      return map[this.currentTab] || '暂无数据'
    },
    
    // 格式化时间
    formatTime(time) {
      if (!time) return ''
      return time.replace('T', ' ').substring(0, 16)
    }
  }
}
</script>

<style scoped>
.tasks-container {
  min-height: 100vh;
  background-color: #f5f7fa;
}

/* 统计卡片 */
.stat-cards {
  display: flex;
  padding: 20rpx;
  gap: 20rpx;
}

.stat-card {
  flex: 1;
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  display: flex;
  align-items: center;
  gap: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
}

.stat-icon {
  width: 60rpx;
  height: 60rpx;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-icon.orange {
  background: rgba(250, 173, 20, 0.1);
}

.stat-icon.blue {
  background: rgba(24, 144, 255, 0.1);
}

.stat-icon.green {
  background: rgba(82, 196, 26, 0.1);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 4rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #999;
}

/* 筛选标签 */
.filter-section {
  background: #fff;
  padding: 20rpx;
  margin-bottom: 2rpx;
}

.filter-tabs {
  display: flex;
  gap: 30rpx;
}

.tab-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 12rpx 24rpx;
  font-size: 28rpx;
  color: #666;
  background: #f5f7fa;
  border-radius: 20rpx;
  transition: all 0.3s;
  position: relative;
}

.tab-item.active {
  background: linear-gradient(135deg, #faad14, #ffc53d);
  color: #fff;
}

.tab-badge {
  padding: 2rpx 8rpx;
  background: #ff4d4f;
  color: #fff;
  font-size: 20rpx;
  border-radius: 20rpx;
  min-width: 32rpx;
  text-align: center;
}

.tab-item.active .tab-badge {
  background: rgba(255, 255, 255, 0.3);
}

/* 列表 */
.list-container {
  height: calc(100vh - 340rpx);
  padding: 20rpx;
}

.task-item {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20rpx;
}

.item-title {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.merchant-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.urgent-badge {
  display: flex;
  align-items: center;
  gap: 4rpx;
  padding: 4rpx 12rpx;
  background: #fff1f0;
  border-radius: 20rpx;
  font-size: 22rpx;
  color: #ff4d4f;
}

.item-no {
  font-size: 26rpx;
  color: #999;
}

.item-content {
  padding: 20rpx 0;
  border-top: 1rpx solid #f0f0f0;
  border-bottom: 1rpx solid #f0f0f0;
}

.content-row {
  display: flex;
  gap: 40rpx;
  margin-bottom: 12rpx;
}

.content-row:last-child {
  margin-bottom: 0;
}

.content-item {
  flex: 1;
  display: flex;
  align-items: center;
  font-size: 26rpx;
}

.content-item .label {
  color: #999;
  margin: 0 8rpx;
}

.content-item .value {
  color: #333;
  flex: 1;
}

.item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20rpx;
}

.goods-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 8rpx;
  flex: 1;
}

.goods-tag {
  padding: 4rpx 12rpx;
  background: #e6f7ff;
  border-radius: 8rpx;
  font-size: 24rpx;
  color: #1890ff;
}

.goods-more {
  padding: 4rpx 12rpx;
  background: #f0f0f0;
  border-radius: 8rpx;
  font-size: 24rpx;
  color: #999;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 6rpx;
  padding: 12rpx 24rpx;
  background: linear-gradient(135deg, #faad14, #ffc53d);
  border-radius: 20rpx;
  font-size: 26rpx;
  color: #fff;
  font-weight: 500;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-text {
  color: #999;
  font-size: 28rpx;
  margin-top: 30rpx;
}

.loading-more {
  padding: 30rpx;
  text-align: center;
}
</style>